"""Abstract board for a 5x7 grid of LEDs """
import pygame
import pygame.locals

RED = (255, 0, 0)
GREY = (154, 154, 147)
LIGHT_GREY = (169, 169, 169)

OFF = 0
ON = 1

def get_grid(orient):
    """Utility grid generator """
    grid = []
    for i in range(1, 6):
        for j in range(1, 8):
            grid.append((j*16 + (j - 1)*4, i*16 + (i - 1)*4, orient))
    return grid
    
            
class Board(object):
    """ Simulates a display grid of LEDs
    
    """
    
    def __init__(self, title, size=(152, 110)):
        """Sets up GUI and internal data """
        pygame.init()
        self.window = pygame.display.set_mode(size)
        pygame.display.set_caption(title)
        self.window.fill(LIGHT_GREY)
        self.screen = pygame.display.get_surface()  
        
        self.grid = get_grid(OFF)
        self.empty_grid = get_grid(OFF)
        self.full_grid = get_grid(ON)
        self.update_grid()
            
        pygame.display.update()    
    
    def update_grid(self):
        """Updates GUI grid according to data grid """
        for coords in self.grid:
            if coords[2] == OFF:
                pygame.draw.circle(self.window, GREY, coords[0:2], 8, 0)
            else:
                pygame.draw.circle(self.window, RED, coords[0:2], 8, 0)
        pygame.display.update()

    def clear(self):
        """Makes grid empty; convenience """
        self.grid = self.empty_grid
        self.update_grid()
        
    def fill(self):
        """Makes grid full; convenience """
        self.grid = self.full_grid
        self.update_grid()

    def dot_flip(self, coords):
        """Makes a certain dot on the grid turn on if off, off if on """
        if coords[0] < 5 and coords[1] < 7:
            loc = coords[0]*7 + coords[1]
            if loc < len(self.grid) and loc >= 0:
                if self.grid[loc][2] == OFF:
                    self.grid[loc] = self.grid[loc][0:2] + (ON,)
                else:
                    self.grid[loc] = self.grid[loc][0:2] + (OFF,)
                self.update_grid()
    
